import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import Layout from '../views/LayOut/LayOut.vue'
import store from '../store/index.js'
const routes = [
  //登陆页面
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/pages/login.vue')
  },

  {
    path: '/',
    name: 'Layout',
    component: Layout,
    //子路由、嵌套路由
    children: [
      {
        path: '/index',
        name: 'index',
        component: () => import('../views/pages/index.vue')
      },
      {
        path: '/roles',
        name: 'roles',
        component: () => import('../views/pages/rolesList.vue')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('../views/pages/userList.vue')
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import('../views/pages/goodsList.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),//使用hash模式
  routes
})
router.beforeEach((to, from, next) => {
  /* to: 即将要进入的目标  from: 当前导航正要离开的路由  next: 是一个函数，表示放行 */
  //判断用户是否登录
  console.log("store", store.state.uInfo);
  const uInfo = store.state.uInfo.userInfo
  if (!uInfo.username) {
    

    if (to.path === "/login") {
      next()//如果用户已经是登录页面，直接放行
      return
    }
    next("/login")//如果用户未登录，跳转到登录页面
  } else {
    next()
  }
})

export default router
